import {getMimiShareList} from './../api/api.js';
import Util from "./util";


//current_path 无得时候跳转页面
function getShareInfoData(current_path) {
  return new Promise((resolve, reject) => {  //实时检测
    const pages = getCurrentPages();//获取加载的页面
    const view = pages[pages.length - 1]; //获取当前页面的对象
    let path = view.route
    if (!view) return false;//如果不存在页面对象 则返回
    const data = view.data

    if (Util.isEmpty(path)) {
      resolve()
      return;
    }

    const current_timestamp = Date.parse(new Date())
    let cache_shareList_expire = wx.getStorageSync("cache_shareList_expire");
    let share_list = wx.getStorageSync('share_list');

    if (Util.isEmpty(share_list) || share_list.length === 0) {
      wx.removeStorageSync("share_list");
    }

    if (share_list && cache_shareList_expire + 1 * 3600 * 1000 > current_timestamp) {
      share_list = share_list ? JSON.parse(share_list) : []

      let flag = true
      let retData = null
      for (const k in share_list) {
        let page = share_list[k].pages
        if (path == page) {
          retData = {
            page: share_list[k].path,
            imgPath: share_list[k].imageUrl,
            share_title: share_list[k].title,
          }
          break
        }
      }

      if (!data.isOverShare && !retData) {

        let shareImg = Util.previewCdnImage("/Uploads/mini/share.png", 750, 0),
          sharePath = Util.getCurrentPath(),
          shareTitle = '饱嗝外卖平台';

        if (share_list) {
          share_list.map((e1, k) => {
            if (e1.pages == 'default') {
              shareImg = Util.previewCdnImage(e1.imageUrl, 750, 0);
              shareTitle = e1.title;
            }
          })
        }

        retData = {
          page: sharePath,
          imgPath: shareImg,
          share_title: shareTitle
        }
      }
      return resolve(retData)
    }
    getMimiShareList().then(res => {
      const share_list = res.data.share_list || null;

      if (share_list) {
        wx.setStorageSync('share_list', JSON.stringify(share_list));
        wx.setStorageSync('cache_shareList_expire', current_timestamp);

        for (const k in share_list) {
          if (path == share_list[k].pages) {
            resolve({
              page: share_list[k].path,
              imgPath: share_list[k].imageUrl,
              share_title: share_list[k].title,
            })
            break
          }
        }
      } else {
        resolve({
          page: 'pages/index/index',
          imgPath: Util.previewCdnImage("/Uploads/mini/share.png", 750, 0),
          share_title: '饱嗝外卖平台'
        })
      }
    }).catch(errmsg => {
      resolve({
        page: path,
        imgPath: Util.previewCdnImage("/Uploads/mini/share.png", 750, 0),
        share_title: '饱嗝外卖平台'
      })
    })
  })
}

module.exports = {
  getShareInfoData: getShareInfoData,
}